#include "UdpClient.hpp"
#include "Common.hpp"
#include <iostream>
#include <string>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>



//客户端要访问服务器，需要知道服务器的ip地址和端口号：从命令行参数传递./udp_client serverip serverport
int main(int argc, char* argv[]){
    if(argc != 3){
        std::cerr << "正确格式为: " << argv[0] << " serverip serverport" << std::endl;
        exit(USAGE_ERROR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //1.创建套接字
    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(socketfd < 0){
        std::cerr << "socket failed" << std::endl;
        exit(SOCKET_ERROR);
    }

    //2.填充服务端信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);

    //3.让客户端不断向服务端发数据
    while(true){
        //3.1 获取用户输入的数据
        std::cout << "please enter# ";
        std::string message;
        std::getline(std::cin, message);

        //客户端也需要有自己的ip和端口！但是客户端不需要自己显示调用bind接口进行绑定
        //而是当客户端首次sendto消息的时候，由OS自动进行宾得绑定
        //3.2 客户端发数据
        int n = sendto(socketfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
        (void)n;

        //4.客户端收消息
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        n = recvfrom(socketfd, buffer, sizeof(buffer)-1, 0, CONV(&temp), &len);
        if(n > 0){
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}